package com.umfwechat.lightprogram.controller.my;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.umfwechat.common.code.RetCode;
import com.umfwechat.common.constant.CommonConsts;
import com.umfwechat.common.prop.UmfPropModel;
import com.umfwechat.util.ReqMessageUtil;
import com.umfwechat.util.StringUtil;

/**
 * 代理商管理    列表；详情；
 * @author llb
 *
 */
@Controller
@RequestMapping("/agentManagement")
public class AgentManagementController {
private static Logger logger = LoggerFactory.getLogger(AgentManagementController.class);
	
	/**
	 * 根据代理商名称查询代理商列表---列表
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/queryAgentByName")
	@ResponseBody
	public JSONObject queryAgentByName(HttpServletRequest request, HttpServletResponse response) throws Exception{	
		JSONObject json= new JSONObject();
		json.put(CommonConsts.RETCODE, RetCode.SUCCESS);
		json.put(CommonConsts.RETMSG, "成功");
		//获取请求参数
		String reqJSON=  (String) request.getAttribute(CommonConsts.REQUESTDATA);
		JSONObject param=JSONObject.fromObject(reqJSON);
		//代理商名称
		String agentName = param.optString("content");
		//当前页
		String pageNo = param.optString("pageNo","1");
		//条数
		String pageSize = param.optString("pageSize","10");
		//代理商编号
		String agentId = param.optString("loginAgentId");
		Integer startNo = Integer.valueOf(pageSize)*(Integer.valueOf(pageNo)-1);	//计算开始行数
		Integer endNo = Integer.valueOf(pageSize)*Integer.valueOf(pageNo);	//计算结束行数
		Map<String, Object> req = ReqMessageUtil.makeReqCrmMap();
		//代理商名称不为空，就设置为请求参数
		if(StringUtil.isNotEmpty(agentName)){	
			req.put("agentName", agentName);
		}
		req.put("startNo", startNo);
		req.put("endNo", endNo);
		req.put("agentId", agentId);
		req.put("orderBy", "agentName");
		req.put("orderRule", "asc");
		Map<String, Object> res = null;
		try {
			XStream xstream = new XStream(new DomDriver());
			// URL配置文件取		
			String url=UmfPropModel.INSTANCE.getPropValue("agent.crm.queryAgentByName");
			logger.info("【根据代理商名称查询代理商列表】接口入参："+req.toString()+"请求路径为"+url);
			res = (Map<String, Object>) com.umfwechat.util.HttpUtil.getResObjPost(url, xstream, req);
		} catch (Exception e) {
			logger.info("查询代理商列表server接口异常",e);
			json.put(CommonConsts.RETCODE, "00434101");
			json.put(CommonConsts.RETMSG, "服务器异常，请稍后再试");
			return json;
		}
		if(res==null){
			json.put(CommonConsts.RETCODE, "00434101");
			json.put(CommonConsts.RETMSG, "服务器异常，请稍后再试");
			return json;
		}
		logger.info("【根据代理商名称查询代理商列表】接口出参："+res.toString());
		String retCode=(String)res.get("retCode");
		if(!"0000".equals(retCode) && !"00060522".equals(retCode)){
			json.put(CommonConsts.RETCODE, "00434101");
			json.put(CommonConsts.RETMSG, "服务器异常，请稍后再试");
			return json;
		}
		Map<String ,Map<String ,String>> map = (Map<String ,Map<String ,String>>) res.get("agentMap");
		if(map==null || map.size()==0){
			json.put("agentList", new ArrayList<>());
			return json;
		}
		List<String> agentIds = (List<String>) res.get("agentIdList");	//排序后的id
		List<Map<String ,String>> agentList=new ArrayList<Map<String,String>>();
		for (String id : agentIds) {
			Map<String, String> mapList = map.get(id);
			Map<String ,String> map2=new HashMap<String, String>();
			map2.put("agentName", mapList.get("agentName"));
			map2.put("linkmanName", mapList.get("linkmanName"));
			map2.put("linkmanMobileId", mapList.get("linkmanMobileId"));
			map2.put("agentRegTime", mapList.get("agentRegTime"));
			map2.put("agentId", mapList.get("agentId"));
			agentList.add(map2);
		}
		json.put("agentList", agentList);
		return json;
	}
	/**
	 * 根据主键查询代理商详情---详情
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/getAgentByPrimaryKey")
	@ResponseBody
	public JSONObject getAgentByPrimaryKey(HttpServletRequest request, HttpServletResponse response) throws Exception{	
		JSONObject json= new JSONObject();
		json.put(CommonConsts.RETCODE, RetCode.SUCCESS);
		json.put(CommonConsts.RETMSG, "成功");
		//获取请求参数
		String reqJSON=  (String) request.getAttribute(CommonConsts.REQUESTDATA);
		JSONObject param=JSONObject.fromObject(reqJSON);
		//代理商名称
		String agentId = param.optString("agentId");
		//查询代理商基本信息
		Map<String, Object> res=getAgentByPrimaryKey(agentId,"0");
		String retCode=(String)res.get("retCode");
		if(!"0000".equals(retCode)){
			json.put(CommonConsts.RETCODE, "00434101");
			json.put(CommonConsts.RETMSG, "服务器异常，请稍后再试");
			return json;
		}
		Map<String ,Map<String ,String>> agentList = (Map<String ,Map<String ,String>>) res.get("agentMap");
		Map<String ,String> agentData = agentList.get(agentId);
		json.put("agentId", agentData.get("agentId"));
		json.put("agentName", agentData.get("agentName"));
		json.put("agentShortName", agentData.get("agentShortName"));
		json.put("registrationNo", agentData.get("organizationId"));
		json.put("busiRegistNum", agentData.get("licenseNo"));
		json.put("userName", agentData.get("linkmanName"));
		json.put("userMobile", agentData.get("linkmanMobileId"));
		//查询代理商管理员信息
		Map<String, Object> reqM = ReqMessageUtil.makeReqCrmMap();
		reqM.put("userName", "admin");
		reqM.put("agentId", agentId);
		Map<String, Object> resM = null;
		try {
			XStream xstream = new XStream(new DomDriver());
			// URL配置文件取		
			String url=UmfPropModel.INSTANCE.getPropValue("agent.crm.queryAgentManager");
			logger.info("【查询代理商管理员信息】接口入参："+reqM.toString()+"请求路径为"+url);
			resM = (Map<String, Object>) com.umfwechat.util.HttpUtil.getResObjPost(url, xstream, reqM);
		} catch (Exception e) {
			logger.info("查询代理商列表server接口异常",e);
			json.put(CommonConsts.RETCODE, "00434101");
			json.put(CommonConsts.RETMSG, "服务器异常，请稍后再试");
			return json;
		}
		if(resM==null){
			json.put(CommonConsts.RETCODE, "00434101");
			json.put(CommonConsts.RETMSG, "服务器异常，请稍后再试");
			return json;
		}
		logger.info("【查询代理商管理员信息】接口出参："+resM.toString());
		String retCodeM=(String)resM.get("retCode");
		if(!"0000".equals(retCodeM)){
			json.put(CommonConsts.RETCODE, "00434101");
			json.put(CommonConsts.RETMSG, "服务器异常，请稍后再试");
			return json;
		}
		List<Map<String,String>> list = (List<Map<String,String>>)resM.get("agentManagerList");
		if(list.size()==0){
			json.put(CommonConsts.RETCODE, "00434104");
			json.put(CommonConsts.RETMSG, "登陆账号不存在");
			return json;
		}
//		Collections.sort(list,new Comparator<Map<String,String>>() {
//			public int compare(Map<String,String> o1, Map<String,String> o2) {
//				String date1 = o1.get("permitLoginTime");
//				String date2 = o2.get("permitLoginTime");
//				DateFormat df= new SimpleDateFormat("MMddHHmmss");
//				try {
//					long time1 = df.parse(date1).getTime();
//					long time2 = df.parse(date2).getTime();
//					return time1>time2 ? 1 : -1;
//				} catch (ParseException e) {
//					logger.info("登录账号排序异常",e);
//					e.printStackTrace();
//					return 0;
//				}
//			}
//		});
		Map map = list.get(0);
		Object assistId = map.get("id");
		Object email = map.get("email");
		json.put("assistId", assistId);
		json.put("email", email);
		return json;
	}
	private Map<String, Object> getAgentByPrimaryKey(String agentId,
			String isQryMer) {
		Map<String, Object> req = ReqMessageUtil.makeReqCrmMap();
		req.put("agentId", agentId);
		//是否附带直拓商户信息0-不查询,1-查询
		req.put("isQryMer", isQryMer);
		Map<String, Object> res = null;
		try {
			XStream xstream = new XStream(new DomDriver());
			// URL配置文件取		
			String url=UmfPropModel.INSTANCE.getPropValue("agent.crm.queryAgent");
			logger.info("【根据主键查询代理商详情】接口入参："+req.toString()+"请求路径为"+url);
			res = (Map<String, Object>) com.umfwechat.util.HttpUtil.getResObjPost(url, xstream, req);
		} catch (Exception e) {
			logger.info("查询代理商列表server接口异常",e);
			res.put(CommonConsts.RETCODE, "00434101");
			res.put(CommonConsts.RETMSG, "服务器异常，请稍后再试");
			return res;
		}
		if(res==null){
			res.put(CommonConsts.RETCODE, "00434101");
			res.put(CommonConsts.RETMSG, "服务器异常，请稍后再试");
			return res;
		}
		logger.info("【根据主键查询代理商详情】接口出参："+res.toString());
		return res;
	}
}
